package hit.dao.database;

import hit.core.HITBase;
import hit.core.Item;
import hit.core.StorageUnit;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Data Access Object that accesses {@link StorageUnit}s in the database
 */
public class DBStorageUnitDAO extends DBBase {

	//private DatabaseDAO databaseDAO;
	
	/**
	 * @param databaseDAO a pointer to the DatabaseDAO that created this
	 * DBStorageUnitDAO
	 * */
	public DBStorageUnitDAO(DatabaseDAO databaseDAO){
		super(databaseDAO);
	}

	@Override
	protected PreparedStatement InitGetQuery() throws SQLException {
		String sql = "SELECT * FROM container WHERE parent_id IS NULL";
		return databaseDAO.GetConnection().prepareStatement(sql);
	}

	@Override
	protected List<HITBase> ProcessGetRS(ResultSet rs) throws SQLException {
		List<HITBase> results = new ArrayList<HITBase>();
		
		while (rs.next()) {
			StorageUnit unit = new StorageUnit(rs.getString(2));
			unit.setId(rs.getInt(1));
			results.add(unit);
		}
		
		return results;
	}

	@Override
	protected List<PreparedStatement> InitCreateStatement(HITBase object) throws SQLException {
		String sql = "INSERT INTO container (name) VALUES (?)";
		String sql2 = "SELECT last_insert_rowid()";
		
		StorageUnit unit = (StorageUnit) object;
		PreparedStatement stmt = databaseDAO.GetConnection().prepareStatement(sql);
		stmt.setString(1, unit.GetName());
		
		PreparedStatement stmt2 = databaseDAO.GetConnection().prepareStatement(sql2);
		
		List<PreparedStatement> stmts = new ArrayList<PreparedStatement>();
		stmts.add(stmt);
		stmts.add(stmt2);
		return stmts;
	}

	@Override
	protected List<PreparedStatement> InitRemoveStatement(HITBase object) throws SQLException {
		String sql = "DELETE FROM container WHERE container_id = ?";
		
		StorageUnit unit = (StorageUnit) object;
		PreparedStatement stmt = databaseDAO.GetConnection().prepareStatement(sql);
		stmt.setInt(1, unit.getId());
		
		List<PreparedStatement> stmts = new ArrayList<PreparedStatement>();
		stmts.add(stmt);
		return stmts;
	}

	@Override
	protected List<PreparedStatement> InitUpdateQuery(HITBase object) throws SQLException {
		List<PreparedStatement> stmts = new ArrayList<PreparedStatement>();
		String sql = "UPDATE container SET name = ? WHERE container_id = ?";
		StorageUnit unit = (StorageUnit) object;
		
		PreparedStatement stmt = databaseDAO.GetConnection().prepareStatement(sql);
		stmt.setString(1, unit.GetName());
		stmt.setInt(2, unit.getId());
		
		stmts.add(stmt);
		return stmts;
	}

}
